package handler

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"gorm.io/gorm"
	"service_base_shop/address_srv/global"
	"service_base_shop/address_srv/model"
	"service_base_shop/address_srv/proto"
)

type Address struct {
}

//获取用户的收件人地址
func (this *Address) GetUserAddr(ctx context.Context, GetUserAddrReq *protopb.GetUserAddrListReq) (*protopb.GetUserAddrListRep, error) {
	addr_list := []*model.Address{}
	if err := global.DB.Table("lr_address").Where("uid = ?", GetUserAddrReq.ID).Order("is_default desc").Find(&addr_list).Error; err != nil {
		return nil, status.Errorf(codes.NotFound, "内部错误！")
	}
	json_data, _ := json.Marshal(addr_list)
	return &protopb.GetUserAddrListRep{
		AddrList: string(json_data),
	}, nil
}

//设置默认值
func (this *Address) SetDefault(ctx context.Context, SetDefaultReq *protopb.SetDefaultReq) (*protopb.SetDefaultRep, error) {
	addr := model.Address{}
	if err := global.DB.Table("lr_address").Where("is_default = 1 and uid = ?", SetDefaultReq.UserID).Select([]string{"id"}).Take(&addr).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, status.Errorf(codes.NotFound, "内部查询错误！")
		}
	}
	if addr.Id != 0 {
		if err := global.DB.Table("lr_address").Where("id = ?", addr.Id).Update("is_default", 0).Error; err != nil {
			return nil, status.Errorf(codes.NotFound, "更新失败！")
		}
	}
	if err := global.DB.Table("lr_address").Where("id = ?", SetDefaultReq.AddrID).Update("is_default", 1).Error; err != nil {
		return nil, status.Errorf(codes.NotFound, "更新失败！")
	}
	return &protopb.SetDefaultRep{
	}, nil
}

//设置默认值
func (this *Address) DelAddr(ctx context.Context, DelAddrReq *protopb.DelReq) (*protopb.DelRep, error) {
	addr := model.Address{}
	if err := global.DB.Table("lr_address").Where("uid = ? and id = ?", DelAddrReq.UserID, DelAddrReq.AddrID).Select([]string{"id"}).Take(&addr).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, status.Errorf(codes.NotFound, "非法请求")
		}
	}
	if err := global.DB.Table("lr_address").Where("id = ?", addr.Id).Delete(&addr).Error; err != nil {
		return nil, status.Errorf(codes.NotFound, "删除失败")
	}
	return &protopb.DelRep{
	}, nil
}

//设置默认值
func (this *Address) GetProvince(ctx context.Context, DelAddrReq *protopb.GetProvinceAddrList) (*protopb.GetSystemAddrListRep, error) {
	addr := []*model.ChinaCity{}
	if err := global.DB.Table("lr_china_city").Where("tid = ?", 0).Order("id asc").Select([]string{"id,name"}).Find(&addr).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetSystemAddrListRep{
				AddrList: "{}",
			}, nil
		}
	}
	addr_lsit, err := json.Marshal(addr)
	if err != nil {
		return nil, status.Errorf(codes.NotFound, "内部错误")
	}
	return &protopb.GetSystemAddrListRep{
		AddrList: string(addr_lsit),
	}, nil
}

func (this *Address) GetCityAddr(ctx context.Context, GetCityAddrReq *protopb.GetCityAddrList) (*protopb.GetSystemAddrListRep, error) {
	seng := GetCityAddrReq.ShengId
	addr := []*model.ChinaCity{}
	if err := global.DB.Table("lr_china_city").Where("tid = ?", 0).Order("id asc").Select([]string{"id,name"}).Find(&addr).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetSystemAddrListRep{
				AddrList: "{}",
			}, nil
		}
	}
	sheng_id := addr[seng-1].ID
	addr = []*model.ChinaCity{}
	if err := global.DB.Table("lr_china_city").Where("tid = ?", sheng_id).Order("id asc").Select([]string{"id,name"}).Find(&addr).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetSystemAddrListRep{
				AddrList: "{}",
			}, nil
		}
	}
	addr_lsit, err := json.Marshal(addr)
	if err != nil {
		return nil, status.Errorf(codes.NotFound, "内部错误")
	}
	return &protopb.GetSystemAddrListRep{
		AddrList: string(addr_lsit),
		Id:       sheng_id,
	}, nil
}

func (this *Address) GetAreaAddr(ctx context.Context, GetAreaAddrReq *protopb.GetAreaAddrList) (*protopb.GetSystemAddrListRep, error) {
	city_id := GetAreaAddrReq.CityId
	sheng_id := GetAreaAddrReq.ShengId
	addr := []*model.ChinaCity{}
	if err := global.DB.Table("lr_china_city").Where("tid = ?", sheng_id).Order("id asc").Select([]string{"id,name"}).Find(&addr).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetSystemAddrListRep{
				AddrList: "{}",
			}, nil
		}
	}
	agea_id := addr[city_id-1].ID
	addr = []*model.ChinaCity{}
	if err := global.DB.Table("lr_china_city").Where("tid = ?", agea_id).Order("id asc").Select([]string{"id,name"}).Find(&addr).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &protopb.GetSystemAddrListRep{
				AddrList: "{}",
			}, nil
		}
	}
	addr_lsit, err := json.Marshal(addr)
	if err != nil {
		return nil, status.Errorf(codes.NotFound, "内部错误")
	}
	return &protopb.GetSystemAddrListRep{
		AddrList: string(addr_lsit),
		Id:       agea_id,
	}, nil
}



//新增地址
func (this *Address) AddAddr(ctx context.Context, AddAddrReq *protopb.Addr) (*protopb.AddAddrRep, error) {
	 address := model.Address{
	 	 Name: AddAddrReq.Name,
		 Tel: AddAddrReq.Tel,
		 Sheng: AddAddrReq.Sheng,
		 City: AddAddrReq.City,
		 Quyu: AddAddrReq.Quyu,
		 Address: AddAddrReq.Address,
		 AddressXq: AddAddrReq.AddressXq,
		 Code: AddAddrReq.Code,
		 Uid: AddAddrReq.Uid,
	 }
	fmt.Println(address)
	china_city := map[string]interface{}{}
	if err := global.DB.Table("lr_china_city").Where("id = ?",address.Sheng).Select([]string{"name"}).Take(&china_city).Error;  err != nil{
		return nil, status.Errorf(codes.NotFound, "获取省失败")
	}
	province_name := china_city["name"]
	if err := global.DB.Table("lr_china_city").Where("id = ?",address.Sheng).Select([]string{"name"}).Take(&china_city).Error;  err != nil{
		return nil, status.Errorf(codes.NotFound, "获取省失败")
	}
	city_name := china_city["name"]
	if err := global.DB.Table("lr_china_city").Where("id = ?",address.Sheng).Select([]string{"name"}).Take(&china_city).Error;  err != nil{
		return nil, status.Errorf(codes.NotFound, "获取省失败")
	}
	quyu_name := china_city["name"]
	address.AddressXq = province_name.(string)+ city_name.(string) + quyu_name.(string) + address.Address
	 if err := global.DB.Table("lr_address").Create(&address).Error; err != nil{
	 	return  nil,status.Errorf(codes.NotFound,"新增失败")
	 }
	 addr,_ := json.Marshal(address)
	return &protopb.AddAddrRep{
		AddAddr: string(addr),
	}, nil
}

